<?php

class CategoryTable extends Doctrine_Table {

    const ACTIVE = 1;
    const PASSIVE = 2;

    public static function getInstance() {
        return Doctrine_Core::getTable('Category');
    }

    public static function retrieveByPK($id, $isActive = null) {
        $q = self::getInstance()->createQuery()
                ->where("id = ?", $id);

        if ($isActive) {
            $q->addWhere('is_active = ?', $isActive);
        }

        return $q->fetchOne();
    }

    public static function getList($isActive = null) {
        $query = self::getInstance()->createQuery();
        if ($isActive) {
            $query->where('is_active = ?', $isActive);
        }

        return $query->execute();
    }

    public static function getForSelect($isAll = false) {
        $pdo = Doctrine_Manager::connection()->getDbh();

        $sql = "
            SELECT c.id,
                   c.name
            FROM category AS c
            WHERE c.is_active = " . self::ACTIVE . "
            ORDER BY c.name ASC";

        $rows = $pdo->query($sql)->fetchAll();

        if ($isAll) {
            return $rows;
        }

        $arr = array();
        foreach ($rows AS $row) {
            $arr[$row['id']] = $row['name'];
        }

        return $arr;
    }

    public static function getNameById($categoryId) {
        $query = self::getInstance()->createQuery()
                ->where('id = ?', $categoryId);
        $result = $query->fetchArray();

        if (count($result)) {
            return $result['0']['name'];
        }

        return;
    }

    public static function getListForSync($categoryId = 0, $syncDate = null) {
        $categoryId = (int) $categoryId;

        $where = array();
        $where[] = "is_active = " . self::ACTIVE;
        if ($categoryId) {
            $where[] = "category_id = $categoryId";
        }
        if (AppTools::validateDate($syncDate, 'Y-m-d H:i:s')) {
            $where[] = AppTools::convertTimezone('updated_at') . " >= '$syncDate'";
        }
        $where = implode(' AND ', $where);

        $sql = "SELECT id,
                        name
                FROM `category`
                WHERE $where
                ORDER BY id";

        $pdo = Doctrine_Manager::connection()->getDbh();
        $rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        return $rows;
    }

}
